package ni;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import main.ChatNI;
import cs.remoteapp.FileMessage;
import cs.remoteapp.Message;

/**
 * Receive a fileMessage
 * Package  ni
 * Project ChatSystemG5 - INSA 4INFOA1 - 2013/2014
 * @author Thomas Vuillemin Martin Conant
 */
public class TcpReceiver extends Tcp{
	
	private ServerSocket serverSocket;
	private Socket clientSocket;
	private InputStream reader;
	private File file;

	/**
	 * Constructor which open a ServerSocket
	 * The TcpReceiver is now ready to be run
	 * @param ni the object ChatNI
	 */
	public TcpReceiver(ChatNI ni){
		super(ni);
		 try {
			 serverSocket = new ServerSocket(ni.PORTfichier);
		 } catch ( IOException e){
			 System.out.println("TcpReceiver could not open socket");
		 	}	
	}
	
	
	/**
	 * Run method
	 * Accept a file on the previously open ServerSocket.
	 * Receive the entire message and save it with the default name : FileReceivebyChatSystem
	 * Once the file is fully received, the socket is closed
	 */
	@Override
	public void run() {
		byte[] buffer = new byte[65536];
		int number;
		InputStream socketStream;
		try {
			System.out.println("TcpReceiver accepting");
			clientSocket = serverSocket.accept();
			System.out.println("TcpReceiver connection established");
			socketStream = clientSocket.getInputStream();
			file=new File("FileReceivebyChatSystem"); // TO DO : choose where to save it

			OutputStream fileStream=new FileOutputStream(file);

			while ((number = socketStream.read(buffer)) != -1) {
			    fileStream.write(buffer,0,number);
			}

			serverSocket.close();
			fileStream.close();
			socketStream.close();
			System.out.println("File received\n");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
	}

}
